<route lang="json5">
{
  style: {
    navigationStyle: 'default',
    navigationBarTitleText: '商家订单',
  },
}
</route>
<template>
  <view class="order-list-page min-h-screen bg-gray-50">
    <view class="bg-white sticky z-10 shadow-sm">
      <view class="tab-container overflow-x-auto">
        <view class="flex border-b">
          <view v-for="(tab, index) in orderTabs" :key="index"
            class="px-4 py-3 text-sm font-medium whitespace-nowrap flex-1 text-center relative"
            :class="queryParams.status === tab.status ? 'text-orange-500' : 'text-gray-600'"
            @click="setActiveTab(tab.status)">
            {{ tab.label }}
            <view v-if="queryParams.status === tab.status" class="absolute bottom-0 left-0 right-0 h-0.5 bg-orange-500">
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- Order List -->
    <view class="p-4">
      <wd-status-tip image="search" tip="暂无订单" v-if="filteredOrders.length == 0" />

      <view v-else class="space-y-4">
        <view v-for="(order, index) in filteredOrders" :key="index"
          class="bg-white rounded-lg shadow-sm overflow-hidden">
          <!-- Order Header -->
          <view class="p-3 border-b border-gray-100 flex justify-between items-center">
            <view class="flex items-center">
              <text class="text-xs text-gray-500">订单编号：{{ order.orderId }}</text>
              <text v-if="order.isUrgent" class="ml-2 px-1.5 py-0.5 bg-red-100 text-red-500 text-xs rounded">
                加急
              </text>
            </view>
            <text class="text-sm font-medium" :class="{
              'text-orange-500': order.status === 0,
              'text-blue-500': order.status === 1,
              'text-green-500': order.status === 3,
              'text-purple-500': order.status === 5,
            }">
              {{ parseStatus(order.status) }}
            </text>
          </view>

          <!-- Order Content -->
          <view class="p-3 flex" @click="openOrderDetail(order)">
            <!-- Product Image -->
            <view class="relative" @click.stop="openImagePreview(order.productImage)">
              <image :src="order.productImage" :alt="order.productName" class="w-20 h-20 object-cover rounded-md" />
              <view class="absolute -bottom-1 -right-1 bg-gray-800/70 text-white text-xs px-1.5 py-0.5 rounded-full">
                x{{ order.totalNum }}
              </view>
            </view>

            <!-- Order Info -->
            <view class="ml-3 flex-1">
              <view class="font-medium text-gray-800 line-clamp-2">{{ order.productName }}</view>

              <view class="mt-1 flex justify-between items-baseline">
                <view>
                  <text class="text-sm text-gray-500">¥{{ order.totalPrice }}</text>
                  <text class="text-xs text-gray-400 ml-1">x{{ order.totalNum }}</text>
                </view>
                <view class="text-sm font-medium">
                  <text class="text-gray-500">合计：</text>
                  <text class="text-orange-500">¥{{ order.totalPrice }}</text>
                </view>
              </view>

              <view class="mt-2 flex flex-wrap text-xs text-gray-500">
                <text class="mr-3" v-if="order.channel == 0">支付方式：微信支付</text>
                <text class="mr-3" v-if="order.channel == 1">支付方式：支付宝支付</text>
                <text>下单时间：{{ order.createTime }}</text>
              </view>

              <view v-if="order.verificationTime" class="mt-1 text-xs text-gray-500">
                核销时间：{{ order.verificationTime }}
              </view>
            </view>
          </view>
          <!-- 0=待支付 1=待核销 2=已核销 3=待评价 4=已完成 5=申请退款 46=款成功 7=订单过期 -->
          <!-- Order Actions -->
          <view class="p-3 border-t border-gray-100 flex justify-end">
            <wd-button size="small" type="primary" v-if="order.status == 4" @click="checkTheEvaluation(order)"
              class="ml-1! mr-1! px-4 py-1.5 border border-gray-400 text-gray-500 rounded-full text-sm">
              查看用户评价
            </wd-button>
          </view>
        </view>
      </view>

      <!-- Loading More Indicator -->
      <view v-if="isLoading" class="mt-4 flex items-center justify-center py-4">
        <view class="w-5 h-5 border-2 border-orange-500 border-t-transparent rounded-full animate-spin mr-2"></view>
        <text class="text-sm text-gray-600">加载更多中...</text>
      </view>

      <!-- End of List Indicator -->
      <view v-if="!isLoading && filteredOrders.length > 0 && total == filteredOrders.length"
        class="mt-4 text-center py-4 text-sm text-gray-500">
        — 已经到底啦 —
      </view>
    </view>

    <wd-popup v-model="showOrderDetail" :closable="true" custom-class="bg-black/60 z-40  w-80 p-4">
      <view class="bg-white rounded-lg w-full max-w-md max-h-[90vh] overflow-y-auto" @click.stop>
        <view class="p-4 border-b border-gray-100 flex justify-between items-center">
          <view class="font-bold text-gray-800">订单详情</view>
        </view>
      </view>
      <view class="p-4">
        <view class="mb-4 pb-4 border-b border-gray-100">
          <view class="flex justify-between items-center">
            <text class="text-gray-600">订单类型</text>
            <text class="font-medium" :class="{
              'text-orange-500': selectedOrder.orderType == '1',
              'text-green-500': selectedOrder.orderType == '2',
              'text-blue-500': selectedOrder.orderType == '3',
              'text-purple-500': selectedOrder.orderType == '4',
            }">
              <text v-if="selectedOrder.orderType == 1">订单</text>
              <text v-if="selectedOrder.orderType == 2">拼团订单</text>
              <text v-if="selectedOrder.orderType == 3">家政订单</text>
              <text v-if="selectedOrder.orderType == 4">转盘订单</text>
            </text>
          </view>

          <view class="flex justify-between items-center">
            <text class="text-gray-600">订单状态</text>
            <text class="font-medium" :class="{
              'text-orange-500': selectedOrder.status == '0',
              'text-green-500': selectedOrder.status == '1',
              'text-purple-500': selectedOrder.status == '3',
              'text-purple-500': selectedOrder.status == '4',
              'text-gray-500': selectedOrder.status == '5',
            }">
              <!-- {{ selectedOrder.status }} -->
              <text v-if="selectedOrder.status == 0">待付款</text>
              <text v-if="selectedOrder.status == 1">待核销</text>
              <text v-if="selectedOrder.status == 3">待评价</text>
              <text v-if="selectedOrder.status == 4">已完成</text>
              <text v-if="selectedOrder.status == 5">已退款</text>
            </text>
          </view>
        </view>

        <!-- Product Info -->
        <view class="mb-4 pb-4 border-b border-gray-100">
          <view class="flex">
            <image :src="selectedOrder.productImage" :alt="selectedOrder.productName"
              class="w-20 h-20 object-cover rounded-md" @click="openImagePreview(selectedOrder.productImage)" />
            <view class="ml-3 flex-1">
              <view class="font-medium text-gray-800">{{ selectedOrder.productName }}</view>
              <view class="mt-1 text-sm w-full flex justify-between text-gray-500">
                <text>¥{{ selectedOrder.totalPrice }}</text>
                <text class="ml-2">x{{ selectedOrder.totalNum }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- Order Info -->
        <view class="space-y-3 text-sm">
          <view class="flex justify-between">
            <text class="text-gray-600">订单编号</text>
            <text class="text-gray-800">{{ selectedOrder.orderId }}</text>
          </view>

          <view class="flex justify-between">
            <text class="text-gray-600">下单时间</text>
            <text class="text-gray-800">{{ selectedOrder.createTime }}</text>
          </view>

          <view v-if="selectedOrder.verificationTime" class="flex justify-between">
            <text class="text-gray-600">核销时间</text>
            <text class="text-gray-800">{{ selectedOrder.verificationTime }}</text>
          </view>

          <view class="flex justify-between">
            <text class="text-gray-600">支付方式</text>
            <text class="text-gray-800" v-if="selectedOrder.channel == '0'">微信支付</text>
            <text class="text-gray-800" v-else-if="selectedOrder.channel == 1">支付宝支付</text>
            <text class="text-gray-800" v-else-if="selectedOrder.channel == 2">转盘赠送</text>
            <text class="text-gray-800" v-else>/</text>
          </view>

          <view class="flex justify-between">
            <text class="text-gray-600">商品金额</text>
            <text class="text-gray-800">¥{{ selectedOrder.totalPrice }}</text>
          </view>

          <view class="flex justify-between font-medium">
            <text class="text-gray-600">实付金额</text>
            <text class="text-orange-500">¥{{ selectedOrder?.payPrice || 0 }}</text>
          </view>

          <view class="flex justify-between font-medium" v-if="selectedOrder.weight">
            <text class="text-gray-600">重量</text>
            <text class="text-orange-500">{{ selectedOrder?.weight || 0 }}kg</text>
          </view>

          <view class="flex justify-between font-medium" v-if="selectedOrder.orderType == 2">
            <text class="text-gray-600">拼团状态</text>
            <text class="text-orange-500" v-if="selectedOrder?.groupStatus == 1">拼团中</text>
            <text class="text-orange-500" v-if="selectedOrder?.groupStatus == 2">已完成</text>
            <text class="text-orange-500" v-if="selectedOrder?.groupStatus == 3">已取消</text>
          </view>

          <view class="flex justify-between font-medium" v-if="selectedOrder.orderType == 3">
            <text class="text-gray-600">联系人</text>
            <text class="text-orange-500">{{ selectedOrder?.realName }}</text>
          </view>

          <view class="flex justify-between font-medium" v-if="selectedOrder.orderType == 3">
            <text class="text-gray-600">手机号</text>
            <text class="text-orange-500">{{ selectedOrder?.userPhone }}</text>
          </view>

          <view class="flex justify-between font-medium" v-if="selectedOrder.orderType == 3">
            <text class="text-gray-600">地址</text>
            <text class="text-orange-500">{{ selectedOrder?.userAddress }}</text>
          </view>

          <view class="flex justify-between font-medium" v-if="selectedOrder.orderType == 3">
            <text class="text-gray-600">上门时间</text>
            <text class="text-orange-500">{{ selectedOrder?.upperTime }}</text>
          </view>
        </view>

        <view class="w-full flex justify-center items-center h-100rpx">
          <view v-if="selectedOrder.orderType == 3"
            class="w-600rpx h-88rpx rounded-44rpx leading-88rpx text-center bg-#cd1300 text-white" @click="addWeight">
            添加重量
          </view>
        </view>
      </view>
    </wd-popup>
    <!-- 订单编号 -->
    <wd-popup v-model="checkTheEvaluationShow" :closable="true">
      <view class="bg-white rounded-lg w-full max-w-md max-h-[90vh] overflow-y-auto" @click.stop>
        <view class="p-4 border-b border-gray-100 flex justify-between items-center">
          <view class="font-bold text-gray-800">订单评论</view>
        </view>
      </view>
      <view class="w-80 p-4 flex flex-col" v-if="evaluationData">
        <view class="w-full h-8 text-3.5 mb-2">
          <text class="text-3 text-gray-400">订单编号：</text>
          {{ evaluationData?.orderId }}
        </view>
        <view class="w-full h-8 text-3.5 mb-2">
          <text class="text-3 text-gray-400">评分：</text>
          {{ evaluationData?.evaluationStar }}
        </view>

        <view class="w-full grid grid-cols-3">
          <image v-for="(image, index) in parseImage(evaluationData?.evaluationImage)" :src="image"
            class="w-full h-20 object-cover rounded-md" mode="scaleToFill" :key="index" />
        </view>
        <view class="mt-2">
          {{ evaluationData?.evaluationContent }}
        </view>

        <view class="mt-2 text-3 text-gray-400">
          {{ evaluationData?.addTime }}
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { http } from '@/utils/http'
// Tab Navigation
const orderTabs = [
  { label: '全部', status: '' },
  { label: '待付款', status: '0' },
  { label: '待核销', status: '1' },
  { label: '待评价', status: '3' },
  { label: '售后/退款', status: '5' },
]

const setActiveTab = (tabId) => {
  queryParams.value.status = tabId
  queryParams.value.pageNum = 1
  loadMoreOrders()
}

const parseStatus = (status) => {
  if (status == 0) {
    return '待付款'
  } else if (status == 1) {
    return '待核销'
  } else if (status == 3) {
    return '待评价'
  } else if (status == 4) {
    return '已完成'
  } else if (status == 5) {
    return '售后/退款'
  }
}

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  status: '',
  storeId: '',
})

const total = ref(0)

const orders = ref([])
const isLoading = ref(false)

const filteredOrders = computed(() => {
  return orders.value
})

const addWeight = () => {
  console.log("add weight")

  uni.showModal({
    title: '请输入重量(kg)',
    content: selectedOrder.value.weight || 0,
    editable: true,
    placeholderText: '请输入重量(kg)',
    success: async (resp) => {
      console.log('resp', resp)
      if (resp.confirm) {
        let res = await http.get("/api/home/addOrderWeight", { orderId: selectedOrder.value.orderId, weight: resp.content })
        if (res.code == 200) {

          uni.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000,
          })
          queryParams.value.pageNum = 1
          loadMoreOrders()
          showOrderDetail.value = false

        }
      }


    }
  })
}

onLoad(({ storeId, status }) => {
  queryParams.value.storeId = storeId

  if (status) {
    queryParams.value.status = status
  }

  loadMoreOrders()
})

onReachBottom(() => {
  if (total.value > orders.value.length) {
    queryParams.value.pageNum = queryParams.value.pageNum + 1
    loadMoreOrders()
  } else {
    uni.showToast({
      title: '没有更多了',
      icon: 'none',
    })
  }
})

// Load more orders
const loadMoreOrders = async () => {
  if (isLoading.value) return

  uni.showLoading()

  isLoading.value = true
  try {
    let res = await http.get('/api/store/queryStoreOrder', queryParams.value)
    if (res.code == 200) {
      orders.value = res.data.orders
      total.value = res.data.total
    }
  } catch (error) {
  } finally {
    isLoading.value = false
    uni.hideLoading()
  }
}

// Image Preview
const showImagePreview = ref(false)
const previewImage = ref('')

const openImagePreview = (image) => {
  previewImage.value = image
  showImagePreview.value = true
}

// Order Detail
const showOrderDetail = ref(false)
const selectedOrder = ref({})

const openOrderDetail = (order) => {
  selectedOrder.value = order
  showOrderDetail.value = true
}

const checkTheEvaluationShow = ref(false)

const evaluationData = ref(null)

const checkTheEvaluation = async (order) => {
  checkTheEvaluationShow.value = true

  let res = await http.post('/api/evaluate/queryOrderId', { orderId: order.orderId })

  if (res.code == 200) {
    evaluationData.value = { ...res.data.evaluate, orderId: order.orderId }
  }
}

const parseImage = (images) => {
  return images.split(',')
}

</script>

<style scoped>
.tab-container {
  scrollbar-width: none;
  /* Firefox */
  -ms-overflow-style: none;
  /* IE and Edge */
}

.tab-container::-webkit-scrollbar {
  display: none;
  /* Chrome, Safari, Opera */
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>
